﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 渐变
{
    public partial class user_CarRentForm : Form
    {
        public user_CarRentForm()
        {
            InitializeComponent();
        }

        public void loadMsg()
        {
            Console.WriteLine("已进入");
            /* this.pageSize = 30;
             this.CurrentPage = 1;
             string sql = "select CId,CName,CPrice,CImg,CNumber,CarInfo.CTypeId,CarTypeInfo.CTypeId,CTitle from CarInfo,CarTypeInfo where CarInfo.CTypeId=CarTypeInfo.CTypeId and CarInfo.CIsDelete=0";
             DataTable dt = DBHelper.ExecuteQuery(sql);
             //设置是否允许自动生成列
             carData.AutoGenerateColumns = false;
             BindPage();*/
            this.source = new DataSet();
            this.pageSize = 10;
            this.CurrentPage = 1;
            string connstring = System.Configuration.ConfigurationSettings.AppSettings["connstring"].ToString();
            SqlConnection conn = new SqlConnection(connstring);
            conn.Open();
            string sql = "select CId,CName,CPrice,CImg,CNumber,CarInfo.CTypeId,CStatus,CarTypeInfo.CTypeId,CTitle from CarInfo,CarTypeInfo where CarInfo.CTypeId=CarTypeInfo.CTypeId and CarInfo.CIsDelete=0";
            carData.AutoGenerateColumns = false;
            DataAdapter adapter = new SqlDataAdapter(sql, conn);
            adapter.Fill(source);

            BindPage();
        }
        private void user_CarRentForm_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;
            loadSearchType();
            loadMsg();
        }

        //格式化数据
        private void carData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if(e.ColumnIndex == 5)
              {
                string status = carData.Rows[e.RowIndex].Cells["status"].Value.ToString();
                if (status == "True")
                {
                    e.Value = "空闲";
                }
                else
                {
                    e.Value = "使用中";
                }
            }
           
            if (carData.Columns[e.ColumnIndex].Name.Equals("Image"))
            //if (demoGrid.Columns[e.ColumnIndex].Name.Equals("img"))
            {

                if (e.Value.GetType() == typeof(string))
                {
                    byte[] str = Convert.FromBase64String(e.Value.ToString().Replace("data:image/jpg;base64,", "").ToString());
                    e.Value = GetImage(str);
                }

            }
        }

        public Image GetImage(byte[] str)
        {
            MemoryStream ms = new MemoryStream(str);
            Image img = System.Drawing.Image.FromStream(ms);
            return img;
        }

        int pageCount = 0;
        public int PageCount
        {
            get
            {
                if (source != null)
                {
                    pageCount = (int)Math.Ceiling(source.Tables[0].Rows.Count * 1.0 / pageSize);
                }
                return pageCount;
            }
        }

        DataSet source;//用于存储数据库中的查询出来的数据
        int pageSize = 5;//每页条目数
        int currentPage = 1;
        /// <summary>
        /// 当前页
        /// </summary>
        public int CurrentPage
        {
            get { return currentPage; }
            set
            {
                if (value <= 1)
                {
                    value = 1;
                    this.bdFirstItem.Enabled = false;
                    this.bdPreviousItem.Enabled = false;
                    this.bdNextItem.Enabled = true;
                    this.bdLastItem.Enabled = true;
                }
                else if (value >= PageCount)
                {
                    value = pageCount;
                    this.bdFirstItem.Enabled = true;
                    this.bdPreviousItem.Enabled = true;
                    this.bdNextItem.Enabled = false;
                    this.bdLastItem.Enabled = false;
                }
                else
                {
                    this.bdFirstItem.Enabled = true;
                    this.bdPreviousItem.Enabled = true;
                    this.bdNextItem.Enabled = true;
                    this.bdLastItem.Enabled = true;

                }
                currentPage = value;
            }
        }
        int currentRow;
        /// <summary>
        /// 每页首行索引
        /// </summary>
        public int CurrentRow
        {
            get
            {
                if (CurrentPage == 1)
                {
                    currentRow = 0;
                }
                else
                {
                    currentRow = (CurrentPage - 1) * pageSize;
                }
                return currentRow;
            }
        }
        int max = 0;
        /// <summary>
        /// 每页行数最大值索引
        /// </summary>
        public int Max
        {
            get
            {
                if (CurrentPage == pageCount)
                {
                    max = source.Tables[0].Rows.Count;
                }
                else
                {
                    max = pageSize * CurrentPage;
                }
                return max;
            }
        }
        /// <summary>
        /// 绑定combobox中的页码
        /// </summary>
        private void BindPage()
        {
            this.bdCountItem.Text = PageCount.ToString();
            this.tspcbo.Items.Clear();
            for (int i = 1; i <= pageCount; i++)
            {
                this.tspcbo.Items.Add("第" + i + "页");
            }
            this.tspcbo.SelectedIndex = 0;
        }
        /// <summary>
        /// 分页绑定数据
        /// </summary>
        private void BindSourceFY()
        {
            DataTable dt = new DataTable();
            //dt.TableName = "tb";//这个可以没有
            //下面这个循环比较有用，没有这个循环直接绑定的话datagridview是不显示数据的
            //原因是在dt这个对象里面那个columns集合是空，所以这个datagridview没有办法自动绑定 列的名字可以根据自己的需要添加想要的名字
            for (int i = 0; i < source.Tables[0].Columns.Count; i++)
            {
                dt.Columns.Add(source.Tables[0].Columns[i].ToString());
            }
            for (int i = CurrentRow; i < Max; i++)
            {
                dt.ImportRow(source.Tables[0].Rows[i]);
            }
            this.carData.DataSource = dt;
            //this.dgv.DataMember = "tb";

        }

        private void tspcbo_SelectedIndexChanged(object sender, EventArgs e)
        {
            CurrentPage = this.tspcbo.SelectedIndex + 1;
            this.bdPositionItem.Text = CurrentPage.ToString();
            BindSourceFY();
        }

        private void bdFirstItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = 0;
        }

        private void bdPreviousItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = CurrentPage - 2;
        }

        private void bdNextItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = CurrentPage;
        }

        private void bdLastItem_Click(object sender, EventArgs e)
        {
            this.tspcbo.SelectedIndex = PageCount - 1;
        }


        public void loadSearchType()
        {
            string sql = "select * from CarTypeInfo where CIsDelete = 0";
            DataTable dt = new DataTable();
            dt = DBHelper.ExecuteQuery(sql);
            DataRow dr = dt.NewRow();
            dr[0] = 0;
            dr[1] = "全部分类";
            dr[2] = 0;
            dt.Rows.InsertAt(dr, 0);
            cmbSearchType.DataSource = dt;
            cmbSearchType.DisplayMember = "CTitle";
            cmbSearchType.ValueMember = "CTypeId";

            cmbSearchType.SelectedIndex = 0;

        }
        private void cmbSearchType_TextChanged(object sender, EventArgs e)
        {
            loadSearch();
        }
        /*搜索*/
        public void loadSearch()
        {
            string sql = "select CId,CName,CPrice,CImg,CNumber,CarInfo.CTypeId,CStatus,CarTypeInfo.CTypeId,CTitle from CarInfo,CarTypeInfo where CarInfo.CTypeId=CarTypeInfo.CTypeId and CarInfo.CIsDelete=0 and CTitle=@ctitle";
            SqlParameter type = new SqlParameter("@ctitle", cmbSearchType.Text);
            if(cmbSearchType.Text == "全部分类")
            {
                loadMsg();
            }
            else
            {
                DataTable dt = new DataTable();
                dt = DBHelper.ExecuteQuery(sql, type);
                carData.AutoGenerateColumns = false;
                carData.DataSource = dt;
            }


        }
        public string operName { get; set; }
        public string carNumber { get; set; }

        private void btnRent_Click(object sender, EventArgs e)
        {
           int numHang = this.carData.CurrentRow.Index;
           string status = this.carData.Rows[numHang].Cells[5].Value.ToString();
           string carNumber = this.carData.Rows[numHang].Cells[3].Value.ToString();
           string price = this.carData.Rows[numHang].Cells[1].Value.ToString();
            string carName = this.carData.Rows[numHang].Cells[2].Value.ToString();
            //汽车租用。如果该汽车状态为true（空闲），则可以出租

            if (status == "True"){
                //可以出租
                MessageBox.Show("可以出租");
         
                user_rentCarForm rentCarForm = new user_rentCarForm();
                rentCarForm.carNumber = carNumber;
                rentCarForm.price = price;
                rentCarForm.carName = carName;
                rentCarForm.opername = this.operName;
                DialogResult dir = rentCarForm.ShowDialog();
               /* rentCarForm.Show();*/
               if(dir == DialogResult.OK)
                {
                    loadMsg();
                }


            }
            else
            {
                this.ShowErrorTip("此车已被租走！请更换车辆！");
            }
        }
    }
}
